package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"quiz-master/cache"
	"quiz-master/model"
	"strconv"
	"time"
)

func BigCarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
		SELECT
		big_car_orders.id as OrderId,
		big_cars.car_code as CarCode,
		big_cars.car_name as CarName,
		big_cars.car_price as CarPrice,
		big_car_orders.order_code as OrderCode,
		big_car_orders.order_price as OrderPrice
		from big_car_orders
		LEFT JOIN big_cars on big_cars.id=big_car_orders.cid
	*/
	var list []model.BigCarOrderList
	redis_key := "redis_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("big_car_orders").
			Select(
				"big_car_orders.id as OrderId",
				"big_cars.car_code as CarCode",
				"big_cars.car_name as CarName",
				"big_cars.car_price as CarPrice",
				"big_car_orders.order_code as OrderCode",
				"big_car_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN big_cars on big_cars.id=big_car_orders.cid").
			Offset(offset).
			Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	model.DB.Model(&model.BigCarOrder{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})
	return
}

func BigCarOrderList(c *gin.Context) {
	id := c.Query("id")
	var list model.BigCarOrderList
	redis_key := "redis_de_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("big_car_orders").
			Select(
				"big_car_orders.id as OrderId",
				"big_cars.car_code as CarCode",
				"big_cars.car_name as CarName",
				"big_cars.car_price as CarPrice",
				"big_car_orders.order_code as OrderCode",
				"big_car_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN big_cars on big_cars.id=big_car_orders.cid").
			Where("big_car_orders.id = ?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
